//
//  Utils.m
//  beautyAccompany
//
//  Created by xiaocankeji on 15/11/3.
//  Copyright © 2015年 xiaocankeji. All rights reserved.
//

#import "Utils.h"
#import "LoginViewController.h"
@implementation Utils

//图片上传前进行的压缩处理,不改变大小比例,尽量压缩到尺寸在1000一下
+(UIImage *)imageWithCompressImage:(UIImage *)image maximum:(NSInteger)maximum
{
    CGFloat w = image.size.width;
    CGFloat h = image.size.height;
    if (w>h) {
        if (w>1000) {
            //图片比较宽,并且比较大,则按照最宽1000比例压缩
            
            UIGraphicsBeginImageContext(CGSizeMake(maximum, h/w*maximum));  //size 为CGSize类型，即你所需要的图片尺寸
            [image drawInRect:CGRectMake(0, 0, maximum, h/w*maximum)];
            UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return scaledImage;
        }
    }else{
        if (h>1000) {
            UIGraphicsBeginImageContext(CGSizeMake(w/h*maximum, maximum));  //size 为CGSize类型，即你所需要的图片尺寸
            [image drawInRect:CGRectMake(0, 0, w/h*maximum, maximum)];
            UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return scaledImage;
        }
    }
    return image;
}
//图片的等比裁剪
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)toSize
{
    CGSize newSize;
    CGRect rect;
    if ((image.size.width / image.size.height) < (toSize.width / toSize.height)) {
        newSize.width = image.size.width;
        newSize.height = image.size.width *toSize.height / toSize.width;
        rect =  CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height);
        //这个上面,xy的位置有时候要反着写,不知道为啥
        //rect =  CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height);
    } else {
        newSize.height = image.size.height;
        newSize.width = image.size.height * toSize.width / toSize.height;
        rect = CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height);
    }
    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef scale:1 orientation:image.imageOrientation];
    UIGraphicsEndImageContext();
    //重要的,必须释放
    CGImageRelease(subImageRef);
    return smallImage;
    //    UIGraphicsBeginImageContext(toSize);  //size 为CGSize类型，即你所需要的图片尺寸
    //    [smallImage drawInRect:CGRectMake(0, 0, toSize.width, toSize.height)];
    //    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    //    UIGraphicsEndImageContext();
    //    return scaledImage;
    
    
}

-(void)viewControllerPrompt:(CGRect)rect Text:(NSString*)text Image:(UIImage*)image{
    
    UIView *promptView = [[UIView alloc]initWithFrame:rect];
    promptView.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    UILabel *promptText = [[UILabel alloc]initWithFrame:CGRectMake(70, (rect.size.height-50)/2, rect.size.width-140, 50)];
    promptText.text = text;
    promptText.numberOfLines = 0;
    promptText.textAlignment = NSTextAlignmentCenter;
    promptText.font=[UIFont fontWithName:FontName size:15];
    promptText.textColor = [UIColor grayColor];
    [promptView addSubview:promptText];
    
    CGFloat imageWidth = DeviceWidth-200;
    
    if (image) {
        UIImageView *promptImage = [[UIImageView alloc]initWithFrame:CGRectMake((rect.size.width-imageWidth)/2, ((rect.size.height)/2)-(imageWidth), imageWidth, imageWidth)];
        [promptImage setContentMode:UIViewContentModeScaleAspectFit];
        promptImage.clipsToBounds = YES;
        promptImage.image = image;
        [promptView addSubview:promptImage];
    }else{
        UIActivityIndicatorView *testActivityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        testActivityIndicator.center = CGPointMake(rect.size.width/2,  (rect.size.height-80)/2);//只能设置中心，不能设置大小
        testActivityIndicator.color = [UIColor blackColor]; // 改变圈圈的颜色为红色； iOS5引入
        [testActivityIndicator startAnimating]; // 开始旋转
        //        [testActivityIndicator stopAnimating]; // 结束旋转
        //        [testActivityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏
        [promptView addSubview:testActivityIndicator];
        
    }
    self.viewPrompt = promptView;
}

/**
 *  //发送透传消息
 *
 *  @return dic 里面key 对应value(string)
 */

+(void)sendCmdMessageCmd:(NSString *)cmd cmdUserObjectId:(NSString *)cmdUserObjectId  ContentDic:(NSDictionary *)dic
{
    EMChatCommand *cmdChat = [[EMChatCommand alloc] init];
    cmdChat.cmd = cmd;
    EMCommandMessageBody *body = [[EMCommandMessageBody alloc] initWithChatObject:cmdChat];
    EMMessage *message = [[EMMessage alloc] initWithReceiver: cmdUserObjectId bodies:@[body]];
    message.messageType = eMessageTypeChat;
    message.ext = [NSDictionary dictionaryWithDictionary:dic];
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
}


//向plist文件中添加新的存储(存储的都是字典)
+ (void)AddToPlistWithPlistName:(NSString *)plistName andDictionary:(NSDictionary *) dic
{
    NSFileManager *f = [NSFileManager defaultManager];
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [path firstObject];
    NSString *plistPath = [filePath stringByAppendingPathComponent:plistName];
    if (![f fileExistsAtPath:plistPath]) {
        [f createFileAtPath:plistPath contents:nil attributes:nil];
    }
    [dic writeToFile:plistPath atomically:YES];
}
//获取plist文件存储的字典
+ (NSDictionary *)plistName:(NSString *)plistName
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [path firstObject];
    NSString *plistPath = [filePath stringByAppendingPathComponent:plistName];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    return dic;
}

//保存聊过天的用户名字,头像
+(void)saveChatUserDataNicknameUser:(MPUser *)user
{
    
    [[ShareData shareData].userDataDic setObject:user forKey:user.objectId];
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUserNicknameHeadurl",[MPUser currentUser].objectId];
    
    NSDictionary *dic = [Utils plistName:plistName];
    NSMutableDictionary *ndic = [NSMutableDictionary dictionaryWithDictionary:dic];
    NSDictionary *userData = [NSDictionary dictionaryWithObjectsAndKeys:user.nickname,@"nickname",user.avatar.url,@"headurl", nil];
    [ndic setObject:userData forKey:user.objectId];
    [Utils AddToPlistWithPlistName:plistName andDictionary:ndic];
}
//获取聊过天的用户名字,头像
+ (NSDictionary *)getChatUserNicknameHeadurlDic
{
    NSString *plistName = [NSString stringWithFormat:@"%@ChatUserNicknameHeadurl",[MPUser currentUser].objectId];
    NSDictionary *dic = [Utils plistName:plistName];
    return dic;
}
//根据用户id获取单个用户的信息
+ (NSDictionary *)getUserNicknameHeadurlObjectId:(NSString *)objectId
{
    NSDictionary *dic = [Utils getChatUserNicknameHeadurlDic];
    return [dic objectForKey:objectId];
}
//是聊过天的用户则更新用户保存的资料
+ (BOOL)isChatUserUpdateUserDataNicknameUser:(MPUser *)user
{
    NSDictionary *dic = [Utils getUserNicknameHeadurlObjectId:user.objectId];
    [Utils saveChatUserDataNicknameUser:user];//无论有没有保存过,都再保存一次
    if (dic) {
       
        return YES;
    }else{
        return NO;
    }
    
    
}

//移动动画
+ (void)animationMobileTimer:(CGFloat )timer View:(UIView*)view Rect:(CGRect)rect{
    [UIView beginAnimations:@"moveAnimation" context:@"move"];//设置动画名称和参数信息.可以用来传值;
    [UIView setAnimationDuration:timer];//设置动画时长
    [UIView setAnimationDelegate:self];//设置动画代理
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];//设置动画缓进缓出
    view.frame=rect;//结束时的坐标;
    [UIView commitAnimations];//提交动画 动画的开始.
}


+(void)alert:(NSString*)msg{
    UIAlertView *alertView=[[UIAlertView alloc]
                            initWithTitle:nil message:msg delegate:nil
                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertView show];
}
+ (void)animationSpringBounciness:(CGFloat )bounciness View:(UIView*)view Rect:(CGRect)rect{
    POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    positionAnimation.toValue = [NSValue valueWithCGRect:rect];
    positionAnimation.springBounciness = bounciness;
    [view.layer pop_addAnimation:positionAnimation forKey:@"animationSpringBounciness"];
}
+ (void)saveToDefaults:(id)obj forKey:(NSString*)key
{
    if ([obj isKindOfClass:[NSNull class]]) {
        obj=@"";
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:obj forKey:key];
    [defaults synchronize];
    
}
+ (id)defaultsForKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}
//退出账号
//一些全局操作
+ (void)quitLogin
{
    // 退订推送
    MPUser *user = [MPUser currentUser];
    AVInstallation *installation = [AVInstallation currentInstallation];
    NSArray *objects;
    if (user.gender==MPUserGender_MALE) {
        objects = @[user.objectId,@"SweetMale"];
    }else{
        objects = @[user.objectId,@"SweetFemale"];
    }
    [installation removeObjectsInArray:objects forKey:@"channels"];
    [installation saveInBackground];
    // 退出登录
    [MPUser logOut];
}
+(CGSize)LabeSizeText:(NSString*)text Font:(UIFont*)font
{
    CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    return size;
}
+(void)pushTabbarHidden:(UIViewController*)viewController Selfvc:(UIViewController*)selfvc
{
    viewController.hidesBottomBarWhenPushed = YES;
    [selfvc.navigationController pushViewController:viewController animated:YES];
}
+(UIView*)Hidden :(UIView*)View Bool:(BOOL)bool2{
    if (bool2==YES) {
        View.alpha = 0;
    }else{
        View.alpha = 1;
    }
    [UIView animateWithDuration:0.25
                     animations:^{
                         if (bool2==YES) {
                             View.alpha = 1;
                         }else{
                             View.alpha = 0;
                         }
                     }];
    return View;
}
+(void)loginVC:(UIViewController*)vc
{
    // 如果未登录跳转到登录页面,默认跳转到主页面
    MPUser *currentUser = [MPUser currentUser];
    [currentUser refreshInBackgroundWithBlock:nil];
    if (!currentUser && currentUser.isUserInited) {
        
    }else{
        // 如果用户已填写了初始化信息
        UINavigationController *Login = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
        Login.modalPresentationStyle = UIModalPresentationFormSheet;
        [vc presentViewController:Login animated:YES completion:nil];
    }
}

+(BOOL)userinit:(UIViewController*)vc
{
    if (![MPUser currentUser].isUserInited) {
        [HUD Prompt:@"请先登录"];
        UINavigationController *Login = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
        Login.modalPresentationStyle = UIModalPresentationFormSheet;
        [vc presentViewController:Login animated:YES completion:nil];
        return NO;
    }
    return YES;
}
@end
